#!/bin/bash
#source ${TOP_DIR}/.config

set -e;

FIRMWARE_ITS_NAME="dynamic-fit-image.its"
KERNEL_ITS_NAME="kernel-fit-image.its"

MKIMAGE_ITS_DIR="${TOP_DIR}/board/${BOARD_NAME}/its"
MKIMAGE_ITS_FIRMWARE="${TOP_DIR}/board/${BOARD_NAME}/its/${FIRMWARE_ITS_NAME}"
MKIMAGE_ITS_KERNEL="${TOP_DIR}/board/${BOARD_NAME}/its/${KERNEL_ITS_NAME}"

GENIMAGE_CFG_DIR="${TOP_DIR}/board/${BOARD_NAME}/genimage_configure"
GENIMAGE_CFG_SD="${GENIMAGE_CFG_DIR}/sdcard.cfg"
GENIMAGE_CFG_SPINOR="${GENIMAGE_CFG_DIR}/spinor.cfg"

ENV_DIR="${TOP_DIR}/board/${BOARD_NAME}/environment"

copy_files_to_images()
{
	rm -rf ${BUILD_DIR}/images/rootfs
	mkdir -p ${BUILD_DIR}/images/rootfs


	cp -rf ${BUILDROOT_BUILD_DIR}/images/* ${BUILD_DIR}/images/
	cp -rf ${MKIMAGE_ITS_FIRMWARE} ${BUILD_DIR}/images/
	cp -rf ${MKIMAGE_ITS_KERNEL} ${BUILD_DIR}/images/

	cd "${BUILD_DIR}/images/rootfs";
	fakeroot -- tar -xvf ../rootfs.tar .
	cd -
}

gen_uboot()
{
	local mkimage="${UBOOT_BUILD_DIR}/tools/mkimage"


	rm -rf ${BUILD_DIR}/images/uboot
	rm -rf ${BUILD_DIR}/images/opensbi
	mkdir -p ${BUILD_DIR}/images/uboot
	mkdir -p ${BUILD_DIR}/images/opensbi

	cp -rf ${UBOOT_BUILD_DIR}/spl/u-boot-spl.bin ${BUILD_DIR}/images/uboot/
	cp -rf ${UBOOT_BUILD_DIR}/spl/u-boot-spl.dtb ${BUILD_DIR}/images/uboot/
	cp -rf ${UBOOT_TPL_BUILD_DIR}/tpl/u-boot-tpl.bin ${BUILD_DIR}/images/uboot/
	cp -rf ${UBOOT_BUILD_DIR}/u-boot-dtb.img ${BUILD_DIR}/images/uboot/
	cp -rf ${UBOOT_BUILD_DIR}/u-boot-nodtb.bin ${BUILD_DIR}/images/uboot/
	cp -rf ${UBOOT_BUILD_DIR}/u-boot.dtb ${BUILD_DIR}/images/uboot/
	cp -rf ${OPENSBI_BUILD_DIR}/platform/${OPENSBI_PLATFORM}/firmware/*.bin ${BUILD_DIR}/images/opensbi

	cd "${BUILD_DIR}/images";
	${mkimage} -f ${BUILD_DIR}/images/${FIRMWARE_ITS_NAME} fw_dynamic.itb
	cd -
}

gen_env_bin()
{
	local mkenvimage="${UBOOT_BUILD_DIR}/tools/mkenvimage"
	cd  "${BUILD_DIR}/images/";
	local default_env_file=${ENV_DIR}/env.txt;

	${mkenvimage} -s 0x4000 -o uboot-env.bin  ${default_env_file}

	cd -
}

gen_linux_bin()
{

	local mkimage="${UBOOT_BUILD_DIR}/tools/mkimage"
	rm -rf ${BUILD_DIR}/images/linux
	mkdir -p ${BUILD_DIR}/images/linux

	cp ${LINUX_BUILD_DIR}/arch/riscv/boot/Image.gz ${BUILD_DIR}/images/linux
	cp -rf ${UBOOT_BUILD_DIR}/u-boot.dtb ${BUILD_DIR}/images/linux/linux.dtb

	cd "${BUILD_DIR}/images";
	${mkimage} -f ${BUILD_DIR}/images/${KERNEL_ITS_NAME} kernel.itb
	cd -
}

gen_image()
{
	local genimage="${TOP_DIR}/tools/genimage";
	local cfg="$1";
	cd "${BUILD_DIR}/images";
	GENIMAGE_TMP="genimage.tmp";
	rm -rf "${GENIMAGE_TMP}"

	${genimage} \
	--rootpath "rootfs/" \
	--tmppath "${GENIMAGE_TMP}" \
	--inputpath "$(pwd)" \
	--outputpath "$(pwd)" \
	--config "${cfg}"

}


copy_files_to_images;
gen_uboot;
gen_env_bin;
gen_linux_bin;
#gen_image ${GENIMAGE_CFG_SD}
gen_image ${GENIMAGE_CFG_SPINOR}
